package server;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.io.*; 
import java.net.*;

class NetworkService implements Runnable { 
  private final ServerSocket serverSocket;
  private final ExecutorService pool;
  /**
   * Thread receipt Client request
 * @param pool
 * @param serverSocket
 */
public NetworkService (ExecutorService pool,
                        ServerSocket serverSocket) {
    this.serverSocket = serverSocket;
    this.pool = pool;
  }
  public void run() { 
    try {

      while ( true ) {

        Socket cs = serverSocket.accept();  //Wait for Clientrequest
        pool.execute(new Handler(serverSocket,cs));
        // Launch new  Handler-Thread to realizes  Realisierung the Clientrequest);
      }
    } catch (IOException ex) {
      System.out.println("--- Interrupt NetworkService-run");
    }
    finally {
      System.out.println("--- Ende NetworkService(pool.shutdown)");
      pool.shutdown();  
      try {
        //wait 4 seconds
        pool.awaitTermination(4L, TimeUnit.SECONDS);
        if ( !serverSocket.isClosed() ) {
          System.out.println("--- Ende NetworkService:ServerSocket close");
          serverSocket.close();
        }
      } catch ( IOException e ) { }
      catch ( InterruptedException ei ) { }
    }
  }
}